﻿using System;
using System.Collections.Generic;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;
using UFIDA.U9.QC.QCDocBE;
using UFIDA.U9.CBO.QC.Enums;
using ufida.u9.ait.openapi;
using UFSoft.UBF.Util.DataAccess;
using UFIDA.U9.PR.PurchaseRequest;
using UFIDA.U9.CBO.MFG.ProductionLine;
using System.Data;




namespace UFIDA.U9.Cust.LS.PlugBE
{
    /// <summary>
    /// 爱发科
    /// 质检单
    /// 删除质检单检验请购单
    /// </summary>
    class AFKQCExtend_bak : IEventSubscriber
    {
        //配置XX.sub.xml文件放置到portal/bin下，dll文件放置到portal/ApplicationServer/Libs下
        public void Notify(params object[] args)
        {
            if (args != null && args.Length != 0 && args[0] is EntityEvent)
            {
                BusinessEntity.EntityKey key = ((EntityEvent)args[0]).EntityKey;
                QCDoc be = key.GetEntity() as QCDoc;// 质检单

                if (be == null)
                    return;

                //if (be.QCDocState == QCDocStateEnum.Checking &&&& qcline.OriginalData.QCDocLineState==QCDocStateEnum.Opening)
                foreach (var qcline in be.QCDocLines)
                {
                    if (qcline.QCDocLineState == QCDocStateEnum.Complete && qcline.OriginalData.QCDocLineState == QCDocStateEnum.Checking)
                    {
                        if (qcline.DescFlexField.PrivateDescSeg5  == "2") continue;//是否需要转下工序
                        if (qcline.IsEligibility2 ==   CalcResultEnum.DisEligibility) continue;//质检标记不合格 跳出
                        if (qcline.DescFlexField.PrivateDescSeg2 == "" )//请购单号为空
                        {
                            PRAITDTOData pr = new PRAITDTOData();
                            pr.DocNo = "PrivateDescSeg8";
                            pr.BusinessDate = be.BusinessDate.ToString();
                            pr.PRDocType = new CopyOfCommonArchiveDataDTOData { Code = "PR3" };
                            pr.Org = new CopyOfCommonArchiveDataDTOData() { ID = be.Org.ID };
                            pr.DescFlexField = new CopyOfDescFlexSegmentsData() { PrivateDescSeg8 = be.DocNo + "-" + qcline.QCDocLineNo.ToString() };
                            if (qcline.Checker == null) { throw new Exception("未录入质检员,请检查"); }

                            pr.ReqEmployee = new CopyOfCommonArchiveDataDTOData { Code = qcline.Checker.Code };// 人员

                            pr.PRLineList = new List<PRLineAITDTOData>();
                            if (qcline.DescFlexField.PrivateDescSeg5 == "1")
                            {
                                PRLineAITDTOData prLine = new PRLineAITDTOData();
                                if (qcline.Checker == null)
                                {
                                    throw new Exception("未录入质检员,请检查");
                                }
                                String checker = qcline.Checker.Code;
                                prLine.ItemInfo = new CopyOfItemInfoData() 
                                {  ItemCode = qcline.DescFlexField.PrivateDescSeg3  };//下工序料品
                                prLine.DocLineNo = qcline.QCDocLineNo;
                                prLine.DescFlexSegments = new CopyOfDescFlexSegmentsData();
                                prLine.DescFlexSegments.PrivateDescSeg6 = "1";// 请购标识
                                if (qcline.QCProject.Code.StartsWith("BK")  || qcline.QCProject.Code.StartsWith("ZX"))    throw new Exception("项目不允许是:BK,ZX开头,请检查");
                                prLine.DescFlexSegments.PrivateDescSeg3 = qcline.QCProject.Code;// 项目qcline.QCProject.Code
                                if (GetPRMO(qcline.SnDocInfo.SrcDocLine.EntityID)== null){ throw new Exception("来源请购单对应料品的生产订单状态不是开工,请检查"); }
                                prLine.DescFlexSegments.PrivateDescSeg2 = GetPRMO(qcline.SnDocInfo.SrcDocLine.EntityID);// 生产订单
                                prLine.DescFlexSegments.PrivateDescSeg5 = GetPRSide(qcline.SnDocInfo.SrcDocLine.EntityID);// side号
                                prLine.DescFlexSegments.PrivateDescSeg11 = GetPRmkh(qcline.SnDocInfo.SrcDocLine.EntityID);//模块号
                                prLine.DescFlexSegments.PrivateDescSeg12 = GetPRdyh(qcline.SnDocInfo.SrcDocLine.EntityID);//单元号
                                prLine.DescFlexSegments.PrivateDescSeg13 = GetPRfh(qcline.SnDocInfo.SrcDocLine.EntityID);//符号
                                prLine.DescFlexSegments.PrivateDescSeg9 = "1";//  默认1 请购数量
                                prLine.Project = new CopyOfCommonArchiveDataDTOData() 
                                { 
                                    Code = qcline.QCProject.Code 
                                };
                                prLine.RequiredDeliveryDate = GetPOdate(qcline.ID);//需求日期 根据出货单取采购订单交期
                                prLine.Memo = $"下工序实物:{qcline.ItemMaster.Name},料号:{qcline.ItemInfo.ItemCode},规格:{qcline.ItemMaster.SPECS}";
                                pr.PRLineList.Add(prLine);
                            }

                            if (pr.PRLineList.Count > 0)
                            {
                                //调用服务
                                PRSaveSV sv = new PRSaveSV();
                                sv.Data = new List<PRAITDTOData> { pr };
                                ufida.u9.ait.openapi.ResultDTOData ret = sv.Do();
                                if (ret.Code != 200) throw new Exception($"创建请购单失败,错误消息:[{ret.Msg}]");
                                if (ret.Code == 200)//回写质检单行
                                {
                                    //修改请购单号
                                    PR.PurchaseRequest.PR prbe;
                                    using (ISession session = Session.Open())
                                    {
                                        prbe = PR.PurchaseRequest.PR.Finder.Find("DescFlexField.PrivateDescSeg8='" + be.DocNo + "-" + qcline.QCDocLineNo.ToString() + "'");
                                        prbe.DocNo = prbe.DocNo + "-GX";
                                        session.Commit();
                                    }
                                    //回写质检单行请购单号
                                    qcline.DescFlexField.PrivateDescSeg2 = prbe.DocNo;
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 获取生产订单号
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        private static string GetMo(string project )
        {
            object docno;
            string sql = $"select mo.docno  from mo_mo mo  left join CBO_Project pro on pro.id=mo.project   left join cbo_itemmaster ite on ite.id=mo.ItemMaster   where pro.code= '{project}'  and ite.Name ='设备本体' group by mo.docno,pro.code,ite.Name";
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out docno);


            return docno.ToString();
        }

        /// <summary>
        /// 获取Side号
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        private static string GetPRSide(long qclid)
        {
            object docno;
            string sql = $"SELECT  top 1   (prl.DescFlexSegments_PrivateDescSeg5) side " +
                $"FROM  QC_QCDocLine qcl   " +
                $"LEFT JOIN PM_RcvLine rcv ON rcv.SrcDoc_SrcDocLine_EntityID= qcl.SnDocInfo_SrcDocLine_EntityID  " +
                $"LEFT JOIN PR_PRLine prl ON prl.id=  rcv.SrcPR_SrcDocLine_EntityID   " +
                $"LEFT JOIN MO_MO mo ON mo.DocNo= prl.DescFlexSegments_PrivateDescSeg2" +
                $"  WHERE mo.DocState=2 and  qcl.SnDocInfo_SrcDocLine_EntityID ='" + qclid + "'";
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out docno);


            return (String)docno;
        }


        /// <summary>
        /// 获取模块号
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        private static string GetPRmkh(long qclid)
        {
            object docno;
            string sql = $"SELECT  top 1   (prl.DescFlexSegments_PrivateDescSeg11) side " +
                $"FROM  QC_QCDocLine qcl   " +
                $"LEFT JOIN PM_RcvLine rcv ON rcv.SrcDoc_SrcDocLine_EntityID= qcl.SnDocInfo_SrcDocLine_EntityID  " +
                $"LEFT JOIN PR_PRLine prl ON prl.id=  rcv.SrcPR_SrcDocLine_EntityID   " +
                $"LEFT JOIN MO_MO mo ON mo.DocNo= prl.DescFlexSegments_PrivateDescSeg2" +
                $"  WHERE mo.DocState=2 and  qcl.SnDocInfo_SrcDocLine_EntityID ='" + qclid + "'";
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out docno);


            return (String)docno;
        }

        /// <summary>
        /// 获取单元号
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        private static string GetPRdyh(long qclid)
        {
            object docno;
            string sql = $"SELECT  top 1   (prl.DescFlexSegments_PrivateDescSeg12) side " +
                $"FROM  QC_QCDocLine qcl   " +
                $"LEFT JOIN PM_RcvLine rcv ON rcv.SrcDoc_SrcDocLine_EntityID= qcl.SnDocInfo_SrcDocLine_EntityID  " +
                $"LEFT JOIN PR_PRLine prl ON prl.id=  rcv.SrcPR_SrcDocLine_EntityID   " +
                $"LEFT JOIN MO_MO mo ON mo.DocNo= prl.DescFlexSegments_PrivateDescSeg2" +
                $"  WHERE mo.DocState=2 and  qcl.SnDocInfo_SrcDocLine_EntityID ='" + qclid + "'";
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out docno);


            return (String)docno;
        }


        /// <summary>
        /// 获取符号
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        private static string GetPRfh(long qclid)
        {
            object docno;
            string sql = $"SELECT  top 1   (prl.DescFlexSegments_PrivateDescSeg13) side " +
                $"FROM  QC_QCDocLine qcl   " +
                $"LEFT JOIN PM_RcvLine rcv ON rcv.SrcDoc_SrcDocLine_EntityID= qcl.SnDocInfo_SrcDocLine_EntityID  " +
                $"LEFT JOIN PR_PRLine prl ON prl.id=  rcv.SrcPR_SrcDocLine_EntityID   " +
                $"LEFT JOIN MO_MO mo ON mo.DocNo= prl.DescFlexSegments_PrivateDescSeg2" +
                $"  WHERE mo.DocState=2 and  qcl.SnDocInfo_SrcDocLine_EntityID ='" + qclid + "'";
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out docno);


            return (String)docno;
        }

        /// <summary>
        /// 获取请购单号
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        private static string GetPR(string prdocno)
        {
            object docno;
            string sql = $"select  docno  from pr_pr  where  DescFlexField_PrivateDescSeg8='" + prdocno+"'";
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out docno);


            return docno.ToString();
        }
        /// <summary>
        /// 获取请购单行生产订单号
        /// </summary>
        /// <param name="qclid"></param>
        /// <returns></returns>
        private static string GetPRMO(long qclid)
        {
            object docno;
            string sql = $"SELECT  top 1   (prl.DescFlexSegments_PrivateDescSeg2) mo " +
                $"FROM  QC_QCDocLine qcl   " +
                $"LEFT JOIN PM_RcvLine rcv ON rcv.SrcDoc_SrcDocLine_EntityID= qcl.SnDocInfo_SrcDocLine_EntityID  " +
                $"LEFT JOIN PR_PRLine prl ON prl.id=  rcv.SrcPR_SrcDocLine_EntityID   " +
                $"LEFT JOIN MO_MO mo ON mo.DocNo= prl.DescFlexSegments_PrivateDescSeg2" +
                $"  WHERE mo.DocState=2 and  qcl.SnDocInfo_SrcDocLine_EntityID ='" + qclid + "'";
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out docno);


            return (String)docno;
        }


        /// <summary>
        /// 根据入库单号 获取采购订单交期
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        private static string GetPOdate(long srclineid)
        {
            // 定义返回的日期字符串
            string deliveryDateStr = string.Empty;
            object result;
            string sql = $"SELECT   top 1 convert(char(10),DeliveryDate ,23) DeliveryDate from PM_PurchaseOrder po left join PM_POLine  line on po.id=line.PurchaseOrder left join PM_POShipLine  ship on ship.POLine=line.id left join PM_RcvLine rcvl on rcvl.SrcDoc_SrcDocLine_EntityID=line.id left join QC_QCDocLine qcl on qcl.SrcDocInfo_SrcDocLine_EntityID=rcvl.id  WHERE  qcl.ID='{srclineid}'";
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out result);


            // 检查查询结果

            if (result != null )
            {
                    // 获取 DeliveryDate
                deliveryDateStr = result.ToString();

                    // 解析日期
                if (DateTime.TryParse(deliveryDateStr, out DateTime deliveryDate))
                {
                    // 如果 DeliveryDate 小于当前日期，则加 30 天
                    if (deliveryDate < DateTime.Today)
                    {
                        deliveryDate = deliveryDate.AddDays(30);
                        deliveryDateStr = deliveryDate.ToString("yyyy-MM-dd");
                    }
                }
            }

            return deliveryDateStr.ToString();
        }

    }
}
